package com.tencent.cloud.iov.recycler.flow;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.subjects.BehaviorSubject;

/**
 * @author showxiao
 * @date 2018/10/17
 */
public abstract class BaseDisposableRecyclerPresenter<M extends RecyclerContract.Loader>
        extends BaseRecyclerPresenter<M> {

    private ObservableTransformer mDisposeTransformer;
    private BehaviorSubject<Boolean> mDisposeSubject;

    protected final <T> ObservableTransformer<T, T> getDisposeTransformer() {
        if (mDisposeTransformer == null) {
            mDisposeTransformer = new ObservableTransformer<T, T>() {

                @Override
                public ObservableSource<T> apply(Observable<T> upstream) {
                    return upstream.takeUntil(getDisposeSubject());
                }
            };
        }

        return (ObservableTransformer<T, T>) mDisposeTransformer;
    }

    private ObservableSource<Boolean> getDisposeSubject() {
        if (mDisposeSubject == null) {
            mDisposeSubject = BehaviorSubject.create();
        }
        return mDisposeSubject;
    }

    @Override
    public void onDestroy() {
        if (mDisposeSubject != null) {
            mDisposeSubject.onNext(true);
            mDisposeSubject = null;
        }
        mDisposeTransformer = null;
        super.onDestroy();
    }
}
